﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class PeiyouLogin : LoginImplBase
    {
        public PeiyouLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = "http://as.peiyou.com/Default.php?m=user&action=loginform&astd=1";
            // qaz55881801 : q123456
            string data = String.Format("username={0}&password={1}&submit=%E7%99%BB%E5%BD%95%E5%B8%90%E5%8F%B7%3E%3E", _acc.UserName, _acc.Password);
            HttpResult resp = TransferMgr.doPostPure(loginurl, data, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string content = resp.getContent();
            if (content.IndexOf("alert") >= 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin; 
                return result; 
            }

            // get url list
            findingServerUrl();
            string gamelisturl = "http://as.peiyou.com/as_server_list.html";
            resp = TransferMgr.doGetPure(gamelisturl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInGetServerList; return result; }

            string retstr = resp.getContent();

            // 查找serverid字符串
            string district_name = String.Format("双线{0}区", translateNumber(_acc.ServerId));
            Regex re = new Regex(String.Format("<a.*href=\"([^\"']*?)\".*>{0}.*</a>", district_name));
            Match m = re.Match(retstr);
            if (m == null || m.Groups == null || m.Groups.Count < 2) { result.StatusCode = LoginStatusCode.FailInFindingGameUrl; return result; }

            string redirecturl = m.Groups[1].Value;

            processRedirect(redirecturl, result, ref cookies);
            return result;
        }
        private string translateNumber(int number)
        {
            string[] numbers = new string[10] { "", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
            string result = number.ToString();
            if (number < 100)
            {
                if (number < 10) result = numbers[number];
                else
                {
                    int tens = number / 10;
                    int remain = number % 10;
                    result = tens > 1 ? numbers[tens] : "" + "十" + numbers[remain];
                }
            }
            return result;
        }
    }
}
